<template>
  <el-breadcrumb
    separator="/"
    class="mb-2"
    :class="{ 'mx-2': useLocale.isMob }"
    style="vertical-align: bottom"
  >
    <el-breadcrumb-item>
      <div class="flex align-center">
        <el-icon :size="18"><Setting /></el-icon>
        <span class="pl">广告推广</span>
      </div>
    </el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/promotion/activity' }"
      >活动列表</el-breadcrumb-item
    >
    <el-breadcrumb-item>{{ rel.title }}</el-breadcrumb-item>
  </el-breadcrumb>

  <el-card class="box-card" shadow="hover">
    <el-scrollbar :class="{scroll:!useLocale.isMob}">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-width="rel.labelWidth"
        class="ec2-form mt-1"
        style="max-width:750px"
        status-icon
      >
        <el-form-item label="活动名称" :label-position="rel.labelPosition" prop="act_name">
          <el-input v-model="form.act_name" :disabled="rel.isDisabled" />
        </el-form-item>
        <el-form-item label="设定预算" :label-position="rel.labelPosition" prop="budget">
          <el-space wrap :size="15">
            <el-input-number
              v-model.number="form.budget"
              :min="30"
              controls-position="right"
              :disabled="rel.isDisabled"
            />
            <div>
              <span class="font-sm mr">余额({{ rel.currency }})</span
              ><span class="font-lg font-weight-bold">{{ rel.balance }}</span>
            </div>
            <el-button type="warning" plain @click="handleRecharge">充值</el-button>
          </el-space>
          <div
            v-if="rel.budgetErr"
            class="mt text-danger font-sm"
            style="width: 100%"
          >
            余额已不足，请充值
          </div>
        </el-form-item>
        <el-form-item label="推广媒体" class="required-self" style="margin-bottom:0;">
          </el-form-item>

          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" label="性别">
            <el-checkbox-group v-model="form.gender" :disabled="rel.isDisabled">
              <el-checkbox
                v-for="item in rel.gender_arr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :checked="item.checked"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" label="年龄">
            <el-checkbox-group v-model="form.age" :disabled="rel.isDisabled">
              <el-checkbox
                v-for="item in rel.age_arr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :checked="item.checked"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" label="区域" style="width: 100%">
            <el-select
              v-model="form.area"
              value-key="id"
              clearable
              placeholder="Select"
              style="width: 100%"
              :disabled="rel.isDisabled"
              @change="changeArea"
            >
              <el-option
                v-for="item in rel.area_arr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" :label="rel.incomeLabel">
            <el-checkbox-group v-model="form.income" :disabled="rel.isDisabled">
              <el-checkbox
                v-for="item in rel.income_arr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" label="媒体分类" style="width: 100%">
            <el-select
              v-model="form.media_category"
              multiple
              clearable
              placeholder="Select"
              style="width: 100%"
              :disabled="rel.isDisabled"
            >
              <el-option
                v-for="item in rel.media_category_arr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" label="媒体标签" style="width: 100%">
            <div class="flex flex-wrap">
              <el-tag
                class="mr mb"
                v-for="tag in form.media_tags"
                :key="tag"
                :closable="!rel.isDisabled"
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="InputRef"
                v-model="inputValue"
                style="width: 100px"
                size="small"
                :disabled="rel.isDisabled"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button
                v-else
                size="small"
                :disabled="rel.isDisabled"
                @click="showInput"
              >
                + 新增标签
              </el-button>
            </div>
          </el-form-item>
          <el-form-item :label-width="rel.labelInnerWidth">
            <el-button
              :disabled="rel.isDisabled"
              type="primary"
              plain
              @click="getMedia"
              >提交</el-button
            >
          </el-form-item>
          <el-form-item label-position="right" :label-width="rel.labelInnerWidth" label="媒体推荐" style="width: 100%">
            <el-select
              v-model="form.media"
              multiple
              clearable
              placeholder="Select"
              style="width: 100%"
              :disabled="rel.isDisabled"
            >
              <el-option
                v-for="item in rel.media_arr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <div v-if="rel.mediaErr" class="mt text-danger font-sm">
              请提交条件后获取媒体推荐
            </div>
          </el-form-item>
        
 
        <el-form-item label-position="right" label="选择贴文" prop="posts" class="required-self">
          <div class="flex flex-column">
            <div>
              <el-button
                :disabled="rel.isDisabled"
                type="primary"
                plain
                @click="openPosts"
                >选择贴文</el-button
              >
              <div v-if="rel.postErr" class="mt text-danger font-sm">
                请选择贴文
              </div>
            </div>
            <div class="mt-1" v-if="form.post.post_platform == 'fb'">
              <div class="mb">贴文ID:{{ form.post.post_id }}</div>
              <div class="flex mb">
                <span class="font text-tips-color mr">{{
                  form.post.post_time
                }}</span>
                <el-link :href="form.post.fb_url" type="primary" target="_blank"
                  >查看原文</el-link
                >
                <span v-if="form.post.fb_url.includes('videos')" class="live"
                  >LIVE</span
                >
              </div>
              <div>{{ form.post.post_content }}</div>
            </div>
            <div class="mt-1" v-if="form.post.post_platform == 'tiktok'">
              <span class="pr">{{ form.post.post_platform }}</span>
              <el-link
                :href="form.post.tiktok_url"
                type="primary"
                target="_blank"
                >查看原文</el-link
              >
            </div>
          </div>
        </el-form-item>
        <el-form-item label-position="right" label="设定排期">
          <el-radio-group v-model="form.start_type" :disabled="rel.isDisabled">
            <el-radio value="immediately">立即</el-radio>
            <el-radio value="schedule">排期</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="form.start_type == 'schedule'"
            v-model="form.start_date"
            placeholder="请选择启动日期"
            type="date"
            :disabled="rel.isDisabled"
            style="width: 100%"
          />
          <div v-if="rel.dateErr" class="mt text-danger font-sm">
            请选择启动日期
          </div>
        </el-form-item>
        <el-form-item label-position="right" label="时长" style="width: 100%">
          <el-select
            v-model="form.duration"
            clearable
            placeholder="Select"
            style="width: 100%"
            :disabled="rel.isDisabled"
          >
            <el-option
              v-for="item in rel.druation_arr"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="foot flex justify-center">
        <el-button
          size="large"
          type="primary"
          :disabled="rel.isDisabled"
          @click="submitForm(formRef)"
        >
          发布
        </el-button>
        <el-button size="large" @click="back()"> 返回 </el-button>
      </div>
    </template>
  </el-card>
  <Posts @sendData="updatePostData"></Posts>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, computed, nextTick } from "vue";
import {
  $getActInfo,
  $mediaRecommend,
  $getBalance,
  $updateAct,
} from "@api/promotion";
import { Search, Setting, Plus } from "@element-plus/icons-vue";
import { useLocaleStore } from "@/store/locales";
import { useRouter,useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const useLocale = useLocaleStore();
const formRef = ref();
const mobDate = new Date();
const rel = reactive({
  type:route.meta.type,
  isDisabled: false,
  title:"",
  balance: 0, //余额
  currency:useLocale.dictionary.currency,//币种
  area_arr: [],
  media_category_arr: [],
  age_arr: [],
  gender_arr: [],
  income_arr: [],
  media_arr: [],
  incomeLabel: "",
  druation_arr: [1, 2, 3, 4, 5],
  postErr:false,
  mediaErr:false,
  dateErr:false,
  budgetErr:false,
  labelWidth:"150",
  labelInnerWidth:"100",
  labelPosition:"right"
});

onMounted(() => {
  if(route.meta.type==='edit'){
  rel.isDisabled=true;
  rel.title="编辑活动"
  }else{
    rel.isDisabled=false;
    rel.title="新增活动"
  }
  if (useLocale.isMob) {
  rel.labelWidth = 'auto';
  rel.labelInnerWidth='100'
  rel.labelPosition="top";
} else {
  rel.labelWidth = '150';
  rel.labelInnerWidth='180'
  rel.labelPosition="right";
}

  getData();
});
const form = reactive({
  act_id: "",
  act_name: "",
  budget: 30,
  area: "",
  media_category: [],
  media_tags: [],
  gender: [],
  age: [],
  income: [],
  media: [],
  post: {},
  start_type: "immediately",
  start_date: "",
  duration: "1",
});
const rules = reactive({
  act_name: [
    {
      required: true,
      message: "Please Input",
      trigger: "blur",
    },
  ],
  budget: [
    {
      required: true,
    },
  ]
});

const getData = async () => {
  console.log(useLocale.dictionary);
  rel.area_arr = useLocale.dictionary.area;
  rel.media_category_arr = useLocale.dictionary.media_category;
  rel.age_arr = useLocale.dictionary.age;
  rel.gender_arr = useLocale.dictionary.gender;
  if(route.meta.type==='edit'){
    getInfo();
  }else{
  form.area = rel.area_arr[0].id;
  rel.incomeLabel = `收入(${rel.area_arr[0].currency})`;
  rel.income_arr = rel.area_arr[0].income;
  }
    getBalance();
};

const getBalance = async () => {
  const res = await $getBalance();
  rel.balance = res.data.balance;
  if(res.data.balance<30){
    rel.budgetErr=true;
  }
};
const getInfo = async () => {
  const res = await $getActInfo();
  if (JSON.stringify(res.data) != "{}") {
    Object.keys(form).forEach((key) => {
      form[key] = res.data[key];
    });
    form.budget=Number(form.budget);
    
    //console.log(typeof(form['budget']))
    //初始化编辑 checkbox
    let i = rel.area_arr.findIndex((item) => item.id === form.area);
    rel.incomeLabel = `收入(${rel.area_arr[i].currency})`;
    rel.income_arr = rel.area_arr[i].income;
    console.log("gender",rel.gender_arr)
    if(res.data['status']==2){
      rel.isDisabled=false;
    }
    getMedia();
    console.log('editform',form)
  }
};
const getMedia = async () => {
  let opts = {
    gender: form.gender,
    age: form.age,
    area: form.area,
    income: form.income,
    media_category: form.media_category,
    media_tags: form.media_tags,
  };
  const res = await $mediaRecommend(opts);
  console.log(res);
  if (res.code == 0) {
    rel.media_arr = res.data.list;
    if(route.meta.type==='create'){
    form.media = res.data.media;
    }
  }
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    console.log(form);
    if (!valid) {
          return false;
        }else if(form.budget>rel.balance){
         rel.budgetErr=true;
        }else if(form.media.length===0){
         rel.mediaErr=true;
        }else if(JSON.stringify(form.post) === '{}'){
          rel.postErr=true;
        }else if(form.start_type=='schedule'&&form.start_date==''){
           rel.dateErr=true;
        }
        else{
          rel.postErr=false;
          rel.mediaErr=false;
           rel.dateErr=false;
          rel.budgetErr=false;
          console.log("submit!");
            // const res = await $updateUserInfo(form);
            // if (res.code == 0) {
            // } else {
            // }
        }
  });
};
function updatePostData(data) {
  form.post = {};
  console.log("updatepost", data);
  if (data.post_platform == "fb") {
    form.post.post_platform = data.post_platform;
    form.post.post_id = data.post.post_id;
    form.post.fb_url = data.post.fb_url;
    form.post.post_time = data.post.post_time;
    form.post.post_content = data.post.post_content;
  }
  if (data.post_platform == "tiktok") {
    form.post.post_platform = data.post_platform;
    form.post.tiktok_url = data.post.tiktok_url;
  }
  console.log("form", form);
}
const back = () => {
  router.push("/promotion/activity");
};
const openPosts = () => {
  useCommon.setShowPosts(true);
};
const changeArea = (value) => {
  form.income = [];
  let i = rel.area_arr.findIndex((item) => item.id === value);
  rel.income_arr = rel.area_arr[i].income;
  rel.incomeLabel = `收入(${rel.area_arr[i].currency})`;
};
const handleChange = async (value) => {
  const res = await $getCode({ region_area_id: value[2] });
  form.region_code = res.data.region_code;
};
//标签
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref();
const handleClose = (tag: string) => {
  form.media_tags.splice(form.media_tags.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    form.media_tags.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
const handleRecharge = () => {
 router.push("/promotion/recharge");
};
const confirm = ({ selectedValue, selectedOptions }) => {
  //date = selectedOptions.slice(1, 3).map((op) => op.text).join('');
  //console.log(date);
  console.log(selectedValue);
  console.log(selectedOptions);
  form.birthday =
    selectedValue[0] + "-" + selectedValue[1] + "-" + selectedValue[2];
  console.log(form);
};
</script>
<style>
.ec2-form {
  .el-form-item__content {
    line-height: 1;
  }
  .el-form-item .el-form-item {
    margin-bottom: 15px;
  }
}
</style>
<style lang="scss" scoped>
.ec2-form {
  
  .live {
    margin-left: 5px;
    border-radius: 3px;
    background: #dd3f4f;
    color: #fff;
    font-size: 10px;
    height: 18px;
    line-height: 18px;
    font-weight: 500;
    padding: 0 5px;
  }

}

.box-card {
  display: inherit;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 20px;
  background: #fff;
  .scroll {
  height: calc(100vh - 320px);
}
.foot{
  max-width:750px;
}
}


</style>
